package com.ywang.hqhp.conf;


import com.ywang.hqhp.exception.IdempotentException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.util.UUID;

@Component
public class TokenService {

    private final RedisService redisService;

    public TokenService(RedisService redisService) {
        this.redisService = redisService;
    }

    public String createToken(){
        String token = UUID.randomUUID().toString().replaceAll("-","");
        redisService.setEx(token,token,3000L);
        return token;
    }

    public boolean checkToken(String token) throws IdempotentException {

        if (StringUtils.isBlank(token)){
             throw new IdempotentException("token不存在");
        }
        if (!redisService.exists(token)){
            throw new IdempotentException("重复请求");
        }
        boolean result = redisService.remove(token);
        if (!result){
            throw new IdempotentException("重复请求");
        }
        return true;
    }
}
